package by.koleda.photoupdater.provider;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import by.koleda.photoupdater.provider.PhotoContract.SuggestionsColumns;
import by.koleda.photoupdater.provider.PhotoContract.VkContactsColumns;

public class PhotoDatabase extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;

	private static final String DATABASE_NAME = "updater.db";

	interface Tables {
		public static final String VKCONTACTS = "vkcontacts";
		public static final String SUGGESTIONS = "suggestions";
	}

	private static final String CREATE_VKCONTACTS_TABLE_SQL = "CREATE TABLE "
			+ Tables.VKCONTACTS + " (" + BaseColumns._ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
			+ VkContactsColumns.CONTACT_ID + " LONG NOT NULL,"
			+ VkContactsColumns.FIRST_NAME + " TEXT,"
			+ VkContactsColumns.LAST_NAME + " TEXT,"
			+ VkContactsColumns.PHOTO_URL + " TEXT,"
			+ VkContactsColumns.HOME_PHONE + " TEXT,"
			+ VkContactsColumns.MOBILE_PHONE + " TEXT)";
	
	private static final String CREATE_SUGGESTIONS_TABLE_SQL = "CREATE TABLE "
			+ Tables.SUGGESTIONS + " (" + BaseColumns._ID
			+ " INTEGER PRIMARY KEY AUTOINCREMENT,"
			+ SuggestionsColumns.CONTACT_ID + " INTEGER NOT NULL,"
			+ SuggestionsColumns.VKCONTACT_ID + " LONG,"
			+ SuggestionsColumns.VKLINKED + " BOOLEAN,"
			+ SuggestionsColumns.VKPOINTS + " INTEGER)";

	private static final String DROP_VKCONTACTS_TABLE_SQL = "DROP TABLE IF EXISTS "
			+ Tables.VKCONTACTS;
	
	private static final String DROP_SUGGESTIONS_TABLE_SQL = "DROP TABLE IF EXISTS "
			+ Tables.SUGGESTIONS;

	public PhotoDatabase(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public final void onCreate(final SQLiteDatabase db) {
		try {
			db.beginTransaction();
			db.execSQL(CREATE_VKCONTACTS_TABLE_SQL);
			db.execSQL(CREATE_SUGGESTIONS_TABLE_SQL);
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}

	}

	public final void onUpgrade(final SQLiteDatabase db, final int oldVersion,
			final int newVersion) {
		try {
			db.beginTransaction();
			db.execSQL(DROP_VKCONTACTS_TABLE_SQL);
			db.execSQL(DROP_SUGGESTIONS_TABLE_SQL);
			db.setTransactionSuccessful();
		} finally {
			db.endTransaction();
		}
		onCreate(db);
	}

}
